package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dot.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;


    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addDish(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增成功");
    }

    @GetMapping("/page")
    public R pageQuery(int page, int pageSize, String name) {
        //菜品表和菜品口味表的分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //过滤条件 模糊查询
        dishLambdaQueryWrapper.like(name != null, Dish::getName, name);
        //排序
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, dishLambdaQueryWrapper);
        //对象拷贝器,a的属性拷贝到b,忽略记录属性
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        //获取菜品表的记录
        List<Dish> records = pageInfo.getRecords();
        //用stream流遍历打印出记录存入集合
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取分类的id
            Long categoryId = item.getCategoryId();
            //根据id查询分类的对象
            Category category = categoryService.getById(categoryId);
            //判断
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setName(categoryName);
            }
            return dishDto;

        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /*
    根据id查询菜品信息和对应的口味信息
     */
    @GetMapping("/{id}")
    //@PathVariable : 该注解可以用来提取url路径中传递的请求参数。
    public R get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);

    }

    /*
    修改菜品
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("菜品修改成功");

    }

    /*
    删除菜品
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {

        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R updatestatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus, status);
        wrapper.in(Dish::getId, ids);
        dishService.update(wrapper);
        return R.success("修改成功");
    }

    /*
      根据条件查询对应的菜品数据
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);
        List<DishDto> dishDtoList = new ArrayList<>();
//遍历 List<Dish> 集合，获取每一个Dish对象，转变成DishDto对象，放入到新的集合 List<DishDto>
        for (Dish dish1 : dishList) {
            DishDto dishDto = new DishDto();
            //1.把dish的属性值copy给dishDto
            BeanUtils.copyProperties(dish1,dishDto);
            //2.查询菜品的口味数据
            // select * from dish_flavor where dish_id = ?
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw1);
            //3.将菜品的口味列表 set给 dishDto
            dishDto.setFlavors(flavors);
            //4.将dishDto放入到 dishDtos 集合中
            dishDtoList.add(dishDto);
        }
            return R.success(dishDtoList);
    }

}